<script setup>
import io from "socket.io-client";
import axios from 'axios'

const baseBackEndServerUrl = "http://localhost:3000";
const baseFrontEndServerUrl = "http://localhost:5173";
var socket = io(baseBackEndServerUrl)

socket.on("connect",()=>{
  console.log("Connected to Server.");
})

socket.on("disconnect",()=>{
  console.log("disconnect from server");
})

socket.on('fileUploaded', (filePath) => {
    console.log("on fileUploaded: filePath="+filePath);
    const link = document.createElement('a');
    link.href = filePath;
    link.download = 'filename.ext';
    link.textContent = 'Download file';

    const div = document.querySelector('#file-list');
    console.log(div);
    div.appendChild(link);
    console.log(div);
});


const CHUNK_SIZE = 1024 * 1024; // 1MB chunk size

async function handleDrop(event) {
    event.preventDefault(); // 阻止浏览器打开文件并显示。
    
    const files = event.dataTransfer.files;
    const file = files[0];
    let start = 0;
    let end = CHUNK_SIZE;

    while (start < file.size) {
      if(end>file.size){
        end = file.size;
      }

      const chunk = file.slice(start, end); // start起始位置包括该位置，end终止位置不包括该位置（也就是说该位置的前一个是包括的）
      const formData = new FormData();
      formData.append('file', chunk);
      console.log("start="+start+"~ end="+end+" / "+ file.size);
      await axios.post('http://localhost:8080/upload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Content-Range': `bytes ${start}-${end}/${file.size}`,
        },
      });

      start = end;
      end = Math.min(end + CHUNK_SIZE, file.size);
    }
}

let filename = "test.pdf"
let download = ""
async function downloadFile() {
      try {
        const response = await axios.get('http://backend-server:8080/download/' + filename, { responseType: 'blob' });
        
        // 生成下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        downloadUrl = url;
        
        // 点击链接进行下载
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
      } catch (error) {
        console.error(error);
      }
}

</script>

<template>
  <div id="file-list"></div>
  <div>
    <textarea @dragover.prevent @drop="handleDrop($event)"></textarea>
  </div>
</template>

<style scoped>

</style>
